package com.rzico.sbl.ui.report

import android.view.inputmethod.EditorInfo
import android.widget.ImageView
import android.widget.TextView
import androidx.core.view.isGone
import androidx.core.view.isVisible
import androidx.core.widget.doOnTextChanged
import com.jeremyliao.liveeventbus.utils.observe
import com.lzy.okgo.model.HttpMethod
import com.rzico.sbl.R
import com.rzico.sbl.databinding.ActivityReportOrderBinding
import com.rzico.sbl.model.*
import com.rzico.sbl.other.*
import com.rzico.sbl.ui.report.other.ReportUrl
import com.rzico.sbl.ui.report.other.goToOrderDetail
import com.rzico.sbl.viewmodel.ReportOrderViewModel
import com.xinnuo.common.extend.*
import com.xinnuo.common.helper.goneAnimation
import com.xinnuo.common.helper.hideSoftInput
import com.xinnuo.common.helper.visibleAnimation
import com.xinnuo.common.listener.onTabSelectedListener
import com.xinnuo.common_ui.base.*
import com.xinnuo.common_ui.glideExt.loadImage
import com.xinnuo.common_ui.utils.*
import com.xinnuo.slimadapter.SlimAdapter
import org.json.JSONObject

class ReportOrderActivity : BaseActivity(R.layout.activity_report_order) {

    private val mBinding by lazy { ActivityReportOrderBinding.bind(getRootView()) }

    private val mShipList = arrayListOf<OrderShipData>()
    private var mState = ""
    private var mKeyWord = ""
    private var mBeginDate = ""
    private var mEndDate = ""

    override fun getViewModel() = get<ReportOrderViewModel>()

    override fun initData() {
        setToolbarVisibility(false)

        initTabLayout()
        initLayout()
        initSearch()
    }

    private fun initTabLayout() {
        val index = intent.getIntExtra("index", 0)

        mBinding
            .orderTab
            .apply {
                onTabSelectedListener {
                    onTabSelected { layout ->
                        layout?.let { tab ->
                            mState = when (tab.position) {
                                1 -> "unpaid"
                                2 -> "unshipped"
                                3 -> "revoked"
                                4 -> "shipped"
                                5 -> "refunding"
                                6 -> "completed"
                                else -> ""
                            }

                            // 批量图标显隐控制
                            when (tab.position) {
                                0, 2 ->
                                    mBinding
                                        .orderBatchFl
                                        .visibleAnimation()

                                else ->
                                    mBinding
                                        .orderBatchFl
                                        .goneAnimation()
                            }

                            // 默认时间筛选项
                            getViewModel()
                                .mAllTimeList
                                .forEach { it.isChecked = false }

                            getViewModel()
                                .mAllTimeList[0]
                                .isChecked = true

                            mBeginDate = ""
                            mEndDate = ""
                            mBinding.orderTime.timeHint.text =
                                getViewModel().mAllTimeList[0].name

                            getViewModel().cancelRequest()
                            getViewModel().delay { updateList() }
                        }
                    }
                }

                addTab(
                    newTab().apply {
                        setCustomView(R.layout.tablayout_item_custom)
                        customView?.find<TextView>(R.id.item_tab_title)?.text = "全部"
                    },
                    index == 0
                )
                addTab(
                    newTab().apply {
                        setCustomView(R.layout.tablayout_item_custom)
                        customView?.find<TextView>(R.id.item_tab_title)?.text = "待确认"
                    },
                    index == 1
                )
                addTab(
                    newTab().apply {
                        setCustomView(R.layout.tablayout_item_custom)
                        customView?.find<TextView>(R.id.item_tab_title)?.text = "待发货"
                    },
                    index == 2
                )
                addTab(
                    newTab().apply {
                        setCustomView(R.layout.tablayout_item_custom)
                        customView?.find<TextView>(R.id.item_tab_title)?.text = "已撤回"
                    },
                    index == 3
                )
                addTab(
                    newTab().apply {
                        setCustomView(R.layout.tablayout_item_custom)
                        customView?.find<TextView>(R.id.item_tab_title)?.text = "已发货"
                    },
                    index == 4
                )
                addTab(
                    newTab().apply {
                        setCustomView(R.layout.tablayout_item_custom)
                        customView?.find<TextView>(R.id.item_tab_title)?.text = "待退款"
                    },
                    index == 5
                )
                addTab(
                    newTab().apply {
                        setCustomView(R.layout.tablayout_item_custom)
                        customView?.find<TextView>(R.id.item_tab_title)?.text = "已完成"
                    },
                    index == 6
                )
            }
    }

    private fun initLayout() {
        mBinding.listLayout.apply {
            emptyLayout.also {
                it.emptyImg.setEmptyImage(
                    resId = R.mipmap.icon_order_no,
                    dpSize = 100f
                )
                it.emptyHint.text = "暂无相关订单信息！"
            }

            recycleList.also { layout ->
                layout.loadLinear(
                    refresh = swipeRefresh,
                    onRefresh = {
                        orderCount()
                        getData(0)
                    },
                    onLoad = {
                        if (!isLoadingMore) {
                            isLoadingMore = true
                            getData(pageNum)
                        }
                    }
                )

                mAdapter = SlimAdapter.creator()
                    .register<OrderHeader>(R.layout.item_order_list_title) { jector, bean, _ ->
                        jector.apply {
                            text(R.id.item_order_time, bean.hint + bean.time)
                            text(R.id.item_order_status, bean.status_hint)

                            clicked {
                                goToOrderDetail(
                                    "orderSn" to bean.orderSN,
                                    "mode" to conditionIf(bean.status == "unpaid", "confirm", ""),
                                    "index" to bean.position
                                )
                            }
                        }
                    }
                    .register<OrderGoods>(R.layout.item_order_list_content) { jector, bean, _ ->
                        jector.apply {
                            text(R.id.item_order_name, bean.name)
                            text(R.id.item_order_type, "规格: ${bean.spec.orEmpty()}")
                            text(R.id.item_order_price, "单价: ${bean.price.formatDecimal()}元")
                            text(R.id.item_order_num, "x${bean.quantity}")

                            with<ImageView>(R.id.item_order_img) {
                                it.loadImage(bean.thumbnail)
                            }

                            with<ImageView>(R.id.item_order_img_type) {
                                when (bean.methodDescr) {
                                    "promotion" -> {
                                        it.visible()
                                        it.setImageResource(R.mipmap.icon_report_v2_03)
                                    }
                                    else -> it.gone()
                                }
                            }

                            clicked {
                                goToOrderDetail(
                                    "orderSn" to bean.orderSN,
                                    "mode" to conditionIf(bean.status == "unpaid", "confirm", ""),
                                    "index" to bean.position
                                )
                            }
                        }
                    }
                    .register<OrderFooter>(R.layout.item_order_list_foot) { jector, bean, _ ->
                        jector.apply {
                            gone(R.id.item_order_hope)
                            text(R.id.item_order_count, bean.total_num)
                            text(R.id.item_order_total, bean.amount.formatDecimal())
                            text(R.id.item_order_name, bean.name)
                            text(R.id.item_order_phone, bean.phone)
                            text(R.id.item_order_addr, bean.address)

                            with<TextView>(R.id.item_order_pei) { tv ->
                                tv.text =
                                    "配送员：${bean.adminName}${bean.adminPhone.ifNotEmpty { " $it" }}"
                                tv.visibility = goneValue { bean.adminName.isEmpty() }
                            }

                            with<TextView>(R.id.item_order_btn1) {
                                it.text = bean.hint_btn1
                                it.visibility = goneValue { bean.hint_btn1.isEmpty() }

                                it.oneClick {
                                    when (bean.status) {
                                        "unpaid" ->
                                            goToOrderDetail(
                                                "orderSn" to bean.orderSN,
                                                "mode" to "confirm",
                                                "index" to bean.position
                                            )
                                        "unshipped" ->
                                            mShipList.isEmpty()
                                                .conditionElse(
                                                    actionTrue = {
                                                        getShipList {
                                                            showSendDialog(
                                                                bean.orderSN,
                                                                bean.position
                                                            )
                                                        }
                                                    },
                                                    actionFalse = {
                                                        showSendDialog(bean.orderSN, bean.position)
                                                    }
                                                )
                                        "revoked" ->
                                            bean.shippingSn.notEmpty {
                                                mShipList.isEmpty()
                                                    .conditionElse(
                                                        actionTrue = {
                                                            getShipList {
                                                                showTransDialog(this, bean.position)
                                                            }
                                                        },
                                                        actionFalse = {
                                                            showTransDialog(this, bean.position)
                                                        }
                                                    )
                                            }
                                    }
                                }
                            }

                            with<TextView>(R.id.item_order_btn2) {
                                it.text = bean.hint_btn2
                                it.visibility = goneValue { bean.hint_btn2.isEmpty() }

                                it.oneClick { printOrder(bean.orderSN, bean.position) }
                            }

                            with<TextView>(R.id.item_order_btn3) { view ->
                                view.text = bean.hint_btn3
                                view.visibility = goneValue { bean.hint_btn3.isEmpty() }

                                view.oneClick {
                                    val items = arrayListOf<ReportCarData>()

                                    when (bean.methodDescr) {
                                        "promotion" -> {
                                            mList
                                                .filter {
                                                    it is OrderGoods
                                                            && !it.isGift
                                                            && it.position == bean.position
                                                }
                                                .mapTo(items) {
                                                    it as OrderGoods
                                                    ReportCarData().apply {
                                                        id = it.goodsId.orEmpty()
                                                        name = it.name
                                                        thumbnail = it.thumbnail
                                                        phPrice = it.price.orEmpty("0.00")
                                                        input = it.quantity
                                                    }
                                                }

                                            startActivityEx<ReportPromoteActivity>(
                                                "orderSn" to bean.orderSN,
                                                "data" to items
                                            )
                                        }
                                        else -> {
                                            mList
                                                .filter {
                                                    it is OrderGoods
                                                            && it.position == bean.position
                                                }
                                                .mapTo(items) {
                                                    it as OrderGoods
                                                    ReportCarData().apply {
                                                        id = it.goodsId.orEmpty()
                                                        name = it.name
                                                        thumbnail = it.thumbnail
                                                        phPrice = it.price.orEmpty("0.00")
                                                        input = it.quantity
                                                    }
                                                }

                                            startActivityEx<ReportGoodsActivity>(
                                                "orderSn" to bean.orderSN,
                                                "data" to items
                                            )
                                        }
                                    }
                                }
                            }

                            with<TextView>(R.id.item_order_btn4) {
                                it.text = bean.hint_btn4
                                it.visibility = goneValue { bean.hint_btn4.isEmpty() }

                                it.oneClick { cancelOrder(bean.orderSN, bean.position) }
                            }

                            clicked {
                                goToOrderDetail(
                                    "orderSn" to bean.orderSN,
                                    "mode" to conditionIf(bean.status == "unpaid", "confirm", ""),
                                    "index" to bean.position
                                )
                            }
                        }
                    }
                    .attachTo(layout)
            }
        }
    }

    private fun initSearch() {
        mBinding
            .orderSearch
            .apply {
                searchEdit.hint = "请输入收货人、电话、地址"
                searchEdit.doOnTextChanged { text, _, _, _ ->
                    text?.let {
                        searchClose.isGone = it.isEmpty()

                        if (it.isEmpty() && mKeyWord.isNotEmpty()) {
                            mKeyWord = ""
                            updateList()
                        }
                    }
                }

                searchEdit.setOnEditorActionListener { _, actionId, _ ->
                    if (actionId == EditorInfo.IME_ACTION_SEARCH) {
                        hideSoftInput() //隐藏软键盘

                        if (searchEdit.text.isBlank()) {
                            showToast("请输入收货人、电话、地址")
                        } else {
                            mKeyWord = searchEdit.textTrim
                            updateList()
                        }
                    }
                    return@setOnEditorActionListener false
                }

                searchClose.oneClick { searchEdit.setText("") }
                searchHint.oneClick {
                    if (searchEdit.text.isBlank()) {
                        showToast("请输入收货人、电话、地址")
                    } else {
                        mKeyWord = searchEdit.textTrim
                        updateList()
                    }
                }
            }
    }

    override fun initListener() {
        mBinding
            .orderTime
            .apply {
                timeLayout.oneClick {
                    getViewModel()
                        .showDropTimeFilter(
                            getIContext(),
                            timeHint,
                            timeHintArrow,
                            timeLayout,
                            getViewModel().mAllTimeList
                        ) { bean ->

                            if (bean.id != "7")
                                getViewModel()
                                    .mAllTimeList
                                    .last()
                                    .name = "自定义时间"

                            when (bean.id) {
                                "0" -> {
                                    mBeginDate = ""
                                    mEndDate = ""

                                    updateList()
                                }
                                "1" -> {
                                    mBeginDate = getTodayDate()
                                    mEndDate = getTodayDate()

                                    updateList()
                                }
                                "2" -> {
                                    mBeginDate = getBeforeDate()
                                    mEndDate = getBeforeDate()

                                    updateList()
                                }
                                "3" -> {
                                    mBeginDate = getMondayDate()
                                    mEndDate = getSundayDate()

                                    updateList()
                                }
                                "4" -> {
                                    mBeginDate = getFirstDate()
                                    mEndDate = getEndDate()

                                    updateList()
                                }
                                "5" -> {
                                    mBeginDate = getBeforeFirstDate()
                                    mEndDate = getBeforeEndDate()

                                    updateList()
                                }
                                "6" -> {
                                    mBeginDate = getYearFirstDate()
                                    mEndDate = getYearEndDate()

                                    updateList()
                                }
                                "7" -> {
                                    showTimeRangeDialog(
                                        isCurrentDate = true,
                                        isAfterLimited = true,
                                        onResult = { start, end ->
                                            getViewModel()
                                                .mAllTimeList
                                                .forEach { it.isChecked = false }

                                            getViewModel()
                                                .mAllTimeList
                                                .last()
                                                .isChecked = true

                                            mBeginDate = start
                                            mEndDate = end
                                            bean.name = "$mBeginDate ~ $mEndDate"
                                            timeHint.text = bean.name

                                            updateList()
                                        }
                                    )
                                }
                            }
                        }
                }
            }

        mBinding
            .orderPrint
            .oneClick {
                startActivityEx<ReportOrderPrintActivity>()
            }

        mBinding
            .orderSend
            .oneClick {
                startActivityEx<ReportOrderShipActivity>()
            }

        observe<String>("orderModify") { updateList() }
    }

    /**
     * 更新自定义Tab数量
     */
    private fun orderCount() {
        getViewModel()
            .orderCount()
            .bindLifeCycle(getLifecycleOwner())
            .subscribeBySuccess(
                event = getViewModel(),
                onSuccess = {
                    val obj = JSONObject(it)
                    getViewModel()
                        .updateNum(
                            obj.optNotNull("unpaid"),
                            obj.optNotNull("unshipped"),
                            obj.optNotNull("revoked"),
                            obj.optNotNull("shipped"),
                            mBinding.orderTab
                        )
                }
            )
    }

    /**
     * 取消订单
     */
    private fun cancelOrder(orderSN: String, index: Int) {
        showHintDialog(
            title = "取消订单",
            hint = "确定要取消订单吗？",
            onSure = {
                getViewModel()
                    .operateOrder(ReportUrl.getBaseUrl().reportDel, orderSN)
                    .bindLifeCycle(getLifecycleOwner())
                    .subscribeBySuccess(
                        event = getViewModel(),
                        onSuccess = {
                            showToast("订单取消成功！")

                            removeItem(index)
                        }
                    )
            }
        )
    }

    /**
     * 打印订单
     */
    private fun printOrder(orderSN: String, index: Int) {
        showHintDialog(
            title = "打印订单",
            hint = "确定要打印订单吗？",
            onSure = {
                getViewModel()
                    .operateOrder(ReportUrl.getBaseUrl().reportPrt, orderSN)
                    .bindLifeCycle(getLifecycleOwner())
                    .subscribeBySuccess(
                        event = getViewModel(),
                        onSuccess = {
                            showToast("订单打印成功！")

                            val item =
                                mList.find { it is OrderFooter && it.position == index } as OrderFooter
                            item.printStatus = "confirmed"
                            item.hint_btn2 = ""
                            item.hint_btn3 = ""

                            mAdapter.notifyDataSetChanged()
                        }
                    )
            }
        )
    }

    /**
     * 显示转派弹框
     */
    private fun showTransDialog(shippingSn: String, index: Int) {
        showListDialog(
            title = "请选择配送站",
            items = mShipList.map { it.name },
            listener = { poistion, _ ->
                getViewModel()
                    .requestBind(
                        requestUrl = ReportUrl.getBaseUrl().reportDis,
                        params = arrayOf(
                            "sn" to shippingSn,
                            "shopId" to mShipList[poistion].id,
                            "memo" to ""
                        )
                    )
                    .bindLifeCycle(getLifecycleOwner())
                    .subscribeBySuccess(
                        event = getViewModel(),
                        onSuccess = {
                            showToast("转派成功！")

                            removeItem(index)
                        }
                    )
            }
        )
    }

    /**
     * 显示发货弹框
     */
    private fun showSendDialog(orderSn: String, index: Int) {
        showListDialog(
            title = "请选择配送站",
            index = mShipList.indexOfFirst { it.id == shopId },
            items = mShipList.map { it.name },
            listener = { positon, _ ->
                getViewModel()
                    .requestBind(
                        requestUrl = ReportUrl.getBaseUrl().rptShip,
                        params = arrayOf(
                            "sn" to orderSn,
                            "shopId" to mShipList[positon].id,
                            "shippingMethod" to "warehouse"
                        )
                    )
                    .bindLifeCycle(getLifecycleOwner())
                    .subscribeBySuccess(
                        event = getViewModel(),
                        onSuccess = {
                            showToast("发货成功！")

                            removeItem(index)
                        }
                    )
            }
        )
    }

    /**
     * 移除item
     */
    private fun removeItem(index: Int) {
        mList.removeAll {
            (it is OrderHeader && it.position == index)
                    || (it is OrderGoods && it.position == index)
                    || (it is OrderFooter && it.position == index)
        }

        mAdapter.notifyDataSetChanged()

        mBinding
            .listLayout
            .emptyLayout
            .emptyView
            .isVisible = mList.isEmpty()

        orderCount()
    }

    /**
     * 获取配送站列表
     */
    private fun getShipList(onNext: () -> Unit) {
        getViewModel()
            .requestModel(
                isLoading = true,
                requestUrl = ReportUrl.getBaseUrl().rptWhere,
                requestMethod = HttpMethod.GET,
                onSuccess = { list ->
                    mShipList.clear()
                    list.mapTo(mShipList) {
                        OrderShipData(
                            it.id,
                            it.name.orEmpty(),
                            it.linkman.orEmpty(),
                            it.telephone.orEmpty()
                        )
                    }
                },
                onFinally = onNext
            )
    }

    /**
     * 报货订单列表
     */
    override fun getData(index: Int, isLoading: Boolean) {
        getViewModel()
            .orderList(
                page = index,
                state = mState,
                keyWord = mKeyWord,
                beginDate = mBeginDate,
                endDate = mEndDate,
                onSuccess = {
                    mList.apply {
                        if (index == 0) {
                            clear()
                            pageNum = 0
                        }
                        addItems(it)
                        if (it.count() > 0) pageNum++
                    }

                    mAdapter.setDataList(mList)
                },
                onFinally = {
                    isLoadingMore = false

                    mBinding
                        .listLayout
                        .apply {
                            swipeRefresh.isRefreshing = false

                            emptyLayout
                                .emptyView
                                .isVisible = mList.isEmpty()
                        }
                }
            )
    }

    /**
     * 刷新列表数据
     */
    private fun updateList() {
        mBinding
            .listLayout
            .apply {
                swipeRefresh.isRefreshing = true

                emptyLayout
                    .emptyView
                    .gone()
            }

        mList.notEmpty {
            clear()
            mAdapter.notifyDataSetChanged()
        }

        orderCount()
        getData(0)
    }

}